import React, { useRef, useState, useEffect } from 'react';
import { useReactToPrint } from 'react-to-print';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { themes } from '../data/themes';
import { getText } from '../data/languages';
import { BsTelephone, BsGenderAmbiguous } from 'react-icons/bs';
import { FaTools, FaBlog, FaBriefcase, FaGraduationCap, FaBirthdayCake, FaTrophy, FaEnvelope, FaMapMarkerAlt, FaBook, FaTasks, FaGripVertical, FaZhihu, FaGithub, FaLink, FaLanguage } from 'react-icons/fa';
// import { SiCsdn } from "react-icons/si";
import { loadYamlFile, getAllYamlFiles } from '../utils/yamlLoader';

// 从 localStorage 获取上次选择的文件
const getLastSelectedFile = () => {
  return localStorage.getItem('selectedResumeFile');
};

// 保存选择的文件到 localStorage
const saveSelectedFile = (filePath) => {
  localStorage.setItem('selectedResumeFile', filePath);
};

// 从 localStorage 获取上次选择的语言
const getLastSelectedLanguage = () => {
  return localStorage.getItem('selectedLanguage') || 'zh';
};

// 保存选择的语言到 localStorage
const saveSelectedLanguage = (language) => {
  localStorage.setItem('selectedLanguage', language);
};

const Resume = () => {
  const [currentTheme, setCurrentTheme] = useState('blue');
  const [sections, setSections] = useState([]);
  const [resumeData, setResumeData] = useState(null);
  const [availableFiles, setAvailableFiles] = useState([]);
  const [currentFile, setCurrentFile] = useState(null);
  const [currentLanguage, setCurrentLanguage] = useState(getLastSelectedLanguage());

  const renderSectionsByData = (data) => {
    const initialSections = [];

    if (data.skills) {
      initialSections.push({ id: 'skills', title: getText(currentLanguage, 'skills'), icon: FaTools });
    }
    if (data.projects) {
      initialSections.push({ id: 'projects', title: getText(currentLanguage, 'projects'), icon: FaTasks });
    }
    if (data.education) {
      initialSections.push({ id: 'education', title: getText(currentLanguage, 'education'), icon: FaGraduationCap });
    }
    if (data.honors) {
      initialSections.push({ id: 'honors', title: getText(currentLanguage, 'honors'), icon: FaTrophy });
    }
    if (data.papers) {
      initialSections.push({ id: 'papers', title: getText(currentLanguage, 'papers'), icon: FaBook });
    }
    if (data.experience) {
      initialSections.push({ id: 'experience', title: getText(currentLanguage, 'experience'), icon: FaBriefcase });
    }
    return initialSections;
  }

  const componentRef = useRef();

  useEffect(() => {
    const files = getAllYamlFiles();
    setAvailableFiles(files);

    // 获取上次选择的文件
    const lastSelected = getLastSelectedFile();
    // 如果有上次选择的文件且该文件仍然可用，则使用它
    if (lastSelected && files.some(file => file.path === lastSelected || file.pathEn === lastSelected)) {
      setCurrentFile(lastSelected);
    } else {
      // 否则使用第一个文件
      setCurrentFile(files[0]?.path);
    }
  }, []);

  useEffect(() => {
    const loadData = async () => {
      if (currentFile) {
        const data = await loadYamlFile(currentFile);
        if (data) {
          setResumeData(data);
          const initialSections = renderSectionsByData(data);
          setSections(initialSections);
        }
      }
    };
    loadData();
  }, [currentFile, currentLanguage]);

  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: resumeData ? `${resumeData?.basicInfo?.name}_${resumeData?.basicInfo?.position}_简历` : '简历',
    onBeforeGetContent: () => {
      document.body.classList.add('print-mode');
      const root = document.documentElement;
      const colors = themes[currentTheme].colors;
      Object.entries(colors).forEach(([key, value]) => {
        root.style.setProperty(`--color-${key}`, value);
      });
      return Promise.resolve();
    },
    onAfterPrint: () => {
      document.body.classList.remove('print-mode');
    },
    removeAfterPrint: true
  });

  useEffect(() => {
    const root = document.documentElement;
    const colors = themes[currentTheme].colors;
    Object.entries(colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value);
    });
  }, [currentTheme]);

  const onDragEnd = (result) => {
    if (!result.destination) return;

    const items = Array.from(sections);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setSections(items);
  }

  // 当文件选择改变时保存选择
  const handleFileChange = (e) => {
    const newFile = e.target.value;
    setCurrentFile(newFile);
    saveSelectedFile(newFile);
  };

  // 当语言选择改变时
  const handleLanguageChange = (language) => {
    setCurrentLanguage(language);
    saveSelectedLanguage(language);
    
    // 更新当前文件路径以匹配选择的语言
    const currentFileObj = availableFiles.find(file => 
      file.path === currentFile || file.pathEn === currentFile
    );
    
    if (currentFileObj) {
      const newPath = language === 'zh' ? currentFileObj.path : currentFileObj.pathEn;
      setCurrentFile(newPath);
      saveSelectedFile(newPath);
    }
  };

  if (!resumeData) {
    return <div className='loading'>{getText(currentLanguage, 'loading')}</div>;
  }

  const renderSection = (section) => {
    const { experience, projects, education, skills, honors, papers } = resumeData;
    switch (section.id) {
      case 'skills':
        return (
          <ul className="skills-list">
            {skills.map((skill, index) => (
              <li key={index}>{skill}</li>
            ))}
          </ul>
        );
      case 'experience':
        return experience.map((exp, index) => (
          <div className="experience-item" key={index}>
            <div className="experience-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '15px', flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                <span className="company-info" style={{ color: '#334155', fontWeight: 600, fontSize: 15 }}>{exp.company}</span>
                <span className="job-title" style={{ color: '#64748b', fontSize: 14 }}>{exp.title}</span>
              </div>
              <span className="experience-period" style={{ color: 'var(--color-extra-light-text)', fontSize: 13 }}>{exp.period}</span>
            </div>
            {exp.responsibilities && exp.responsibilities.length > 0 && (
              <div className="experience-responsibilities enhanced-block">
                {/* <div className="section-subtitle enhanced-title">
                  <span className="vertical-bar"></span>
                  {getText(currentLanguage, 'workResponsibilities')}
                </div> */}
                <ul className="enhanced-list">
                  {exp.responsibilities.map((item, i) => (
                    <li key={i}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {exp.achievements && exp.achievements.length > 0 && (
              <div className="experience-achievements enhanced-block">
                <div className="section-subtitle enhanced-title">
                  <span className="vertical-bar"></span>{getText(currentLanguage, 'workResults')}
                </div>
                <ul className="enhanced-list">
                  {exp.achievements.map((achievement, i) => (
                    <li key={i}>{achievement}</li>
                  ))}
                </ul>
              </div>
            )}
            {/* 新增：项目时间线 */}
            {exp.projects && exp.projects.length > 0 && (
              <div className="experience-projects">
                {/* <div className="projects-timeline-title">{getText(currentLangua ge, 'relatedProjects')}：</div> */}
                <ul className="projects-timeline">
                  {exp.projects.map((project, pi) => (
                    <li key={pi} className="project-timeline-item">
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                        <div className="project-name">{project.name}</div>
                        {project.technologies && project.technologies.length > 0 && (
                          <div className="tech-tags">
                            {project.technologies.map((tech, ti) => (
                              <span className="tech-tag" key={ti}>{tech}</span>
                            ))}
                          </div>
                        )}
                      </div>
                      {project.background && (
                        <div className="project-background">
                          <p><strong>{getText(currentLanguage, 'projectOverview')}：</strong>{project.background}</p>
                        </div>
                      )}
                      {project.responsibilities && project.responsibilities.length > 0 && (
                        <div className="project-responsibilities">
                          <ul>
                            {project.responsibilities.map((item, ri) => (
                              <li key={ri}>{item}</li>
                            ))}
                          </ul>
                        </div>
                      )}
                      {project.results && (
                        <div className="project-results">
                          <p ><strong>{getText(currentLanguage, 'effect')}：</strong><span dangerouslySetInnerHTML={{ __html: project.results }} /></p>
                        </div>
                      )}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        ));
      case 'projects':
        // 只渲染全局 projects
        return projects && projects.length > 0 && projects.map((project, index) => (
          <div className="project-item" key={index}>
            <div className="project-header">
              <div className="project-title-row" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '10px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', minWidth: 0, flex: 1 }}>
                  <h3 className="project-name" style={{ margin: 0, fontSize: 15, fontWeight: 600, color: 'var(--color-title)', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>{project.name}</h3>
                  {project.technologies && project.technologies.length > 0 && (
                    <div className="tech-tags" style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                      {project.technologies.map((tech, i) => (
                        <span className="tech-tag" key={i}>{tech}</span>
                      ))}
                    </div>
                  )}
                </div>
                {project.period && (
                  <div className="project-period" style={{ color: 'var(--color-extra-light-text)', fontSize: 13, whiteSpace: 'nowrap', marginLeft: 'auto' }}>{project.period}</div>
                )}
              </div>
            </div>
            {project.background && (
              <div className="project-background">
                <p><strong>{getText(currentLanguage, 'projectOverview')}：</strong>{project.background}</p>
              </div>
            )}
            {project.responsibilities && project.responsibilities.length > 0 && (
              <div className="project-responsibilities">
                <ul>
                  {project.responsibilities.map((item, i) => (
                    <li key={i}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {project.results && (
              <div className="project-results">
                <p ><strong>{getText(currentLanguage, 'effect')}：</strong><span dangerouslySetInnerHTML={{ __html: project.results }} /></p>
              </div>
            )}
          </div>
        ));
      case 'education':
        return education.map((edu, index) => (
          <div className="education-item" key={index}>
            <div className="education-row">
              <span className="school-name">{edu.school}</span>
              <span className="degree-name">{edu.degree}</span>
              <span className="education-type">{edu.type}</span>
              <span className="education-period">{edu.period}</span>
            </div>
          </div>
        ));
      case 'honors':
        return honors && (
          <div className="honors-list">
            {honors.map((honor, index) => (
              <div className="honor-item" key={index}>
                <div className="honor-main">
                  <span className="honor-name">{honor.name}</span>
                  <span className="honor-issuer">{honor.issuer}</span>
                </div>
                <span className="honor-date">{honor.date}</span>
              </div>
            ))}
          </div>
        );
      case 'papers':
        return papers && (
          <div className="papers-list">
            {papers.map((paper, index) => (
              <div className="paper-item" key={index}>
                <div className="paper-main">
                  <span className="paper-title">{paper.title}</span>
                  <span className="paper-authors">{paper.authors}</span>
                </div>
                <div className="paper-info">
                  <span className="paper-journal">{paper.journal}</span>
                  <span className="paper-index">{paper.index}</span>
                  <span className="paper-year">{paper.year}</span>
                </div>
              </div>
            ))}
          </div>
        );
      default:
        return null;
    }
  }

  const { basicInfo } = resumeData;

  if (!basicInfo) {
    return <div>{getText(currentLanguage, 'loading')}</div>;
  }

  const renderBlogIcons = (blogs) => {
    return blogs.map((blog, index) => {
      let IconComponent;
      switch (blog.platform.toLowerCase()) {
        case 'zhihu':
          IconComponent = FaZhihu;
          break;
        case 'csdn':
          IconComponent = FaBlog;
          break;
        case 'github':
          IconComponent = FaGithub;
          break;
        default:
          return null;
      }
      return (
        <>
          {/* <IconComponent className="info-icon" /> */}
          <IconComponent className="info-icon" style={{ fontSize: '28px' }} />
          <a key={index} href={blog.url} target="_blank" rel="noopener noreferrer" className='blog-icon-link'>

            <span>{getText(currentLanguage, 'blogs')}</span>
          </a>
        </>
      );
    });
  };

  return (
    <>
      <div className="toolbar">
        <div className="toolbar-group">
          <div className="file-selector">
            <select
              value={currentFile}
              onChange={handleFileChange}
              className="file-select"
            >
              {availableFiles.map((file) => (
                <option key={file.path} value={currentLanguage === 'zh' ? file.path : file.pathEn}>
                  {currentLanguage === 'zh' ? file.name : file.nameEn}
                </option>
              ))}
            </select>
          </div>
          
          {/* 语言切换 */}
          <div className="language-selector">
            <button
              className={`language-button ${currentLanguage === 'zh' ? 'active' : ''}`}
              onClick={() => handleLanguageChange('zh')}
            >
              {getText(currentLanguage, 'chinese')}
            </button>
            <button
              className={`language-button ${currentLanguage === 'en' ? 'active' : ''}`}
              onClick={() => handleLanguageChange('en')}
            >
              {getText(currentLanguage, 'english')}
            </button>
          </div>
          
          <div className="theme-selector">
            {Object.entries(themes).map(([key, theme]) => (
              <button
                key={key}
                className={`theme-button ${currentTheme === key ? 'active' : ''}`}
                onClick={() => setCurrentTheme(key)}
                style={{ '--theme-color': theme.colors.primary }}
              >
                {theme.name}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="resume" ref={componentRef}>
        <header className="header">
          <h1>{basicInfo.name}</h1>
          <div className="position-title">{basicInfo.position}</div>
          <div className="basic-info">
            <div className="info-item">
              <BsGenderAmbiguous className="info-icon" />
              <span>{basicInfo.gender}</span>
            </div>
            <div className="info-item">
              <FaBirthdayCake className="info-icon" />
              <span>{basicInfo.age}</span>
            </div>
            <div className="info-item">
              <FaGraduationCap className="info-icon" />
              <span>{basicInfo.education.school} · {basicInfo.education.degree}</span>
            </div>
            <div className="info-item">
              <FaLanguage className="info-icon" />
              <span>CET6:{basicInfo.cet6}</span>
            </div>
          </div>
          <div className="contact-info">
            <div className="info-item">
              <BsTelephone className="info-icon" />
              <span>{basicInfo.contact.phone}</span>
            </div>
            <div className="info-item">
              <FaEnvelope className="info-icon" />
              <span>{basicInfo.contact.email}</span>
            </div>

            {
              basicInfo.contact.address && (
                <div className="info-item">
                  <FaMapMarkerAlt className="info-icon" />
                  <span>{basicInfo.contact.address}</span>
                </div>
              )
            }

          </div>
        </header>

        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="sections">
            {(provided) => (
              <div {...provided.droppableProps} ref={provided.innerRef}>
                {sections.map((section, index) => (
                  <Draggable key={section.id} draggableId={section.id} index={index}>
                    {(provided, snapshot) => (
                      <section
                        className={`section section-${section.id} ${snapshot.isDragging ? 'dragging' : ''}`}
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                      >
                        <div className="section-header">
                          <div className="drag-handle" {...provided.dragHandleProps}>
                            <FaGripVertical className="drag-icon" />
                          </div>
                          <section.icon className="section-icon" />
                          <h2 className="section-title">{section.title}</h2>
                        </div>
                        {renderSection(section)}
                      </section>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </div>

      <button onClick={handlePrint} className="print-button">
        {getText(currentLanguage, 'exportPDF')}
      </button>
    </>
  );
};

export default Resume;